package com.padbot.qm.security;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class UserSessionContainer {
	
	private static UserSessionContainer instance = new UserSessionContainer();
	
	private static Logger logger = LoggerFactory.getLogger(UserSessionContainer.class);
	
	private static Map<String, UserSessionBean> container = new HashMap<String, UserSessionBean>();
	
	private UserSessionContainer() {
		
	}
	
	public static UserSessionContainer getInstance(){
		return instance;
	}

	public void put(String token, UserSessionBean sessionBean){
		container.put(token, sessionBean);
		logger.debug("Container has "+container.size()+" users");
	}
	
	public void remove(String token){
		if(container.containsKey(token)){
			container.remove(token);
		}
		logger.debug("Container has "+container.size()+" users");
	}
	
	public UserSessionBean get(String token){
		return container.get(token);
	}
	
	public void startWatch(){
		Runnable runnable = new Runnable() {  
            public void run() {  
            	logger.debug("Start expired usersession...");
            	List<String> expried = new ArrayList<String>();
                if(container != null && container.size() > 0){
                	Iterator<String> it = container.keySet().iterator();
                	while(it.hasNext()){
                		String key = it.next();
                		UserSessionBean bean = container.get(key);
                		if(!bean.getToken().isActive()){
                			expried.add(key);
                		}
                	}
                }
                logger.debug("Usersession expired count: "+container.size());
                if(expried.size() > 0){
            		for(String key : expried){
                		if(container.containsKey(key)){
                			container.remove(key);
                		}
                	}
            	}
                
            }  
        };
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(runnable, 60, 600, TimeUnit.SECONDS);
	}
	
}
